import dayjs from 'dayjs'

type DateValue = string | number

interface HookOptions {
  // 默认范围
  default?: [DateValue, DateValue]
  // 是否禁用选择未来日期
  disableFuture?: boolean
  // 最大可选取范围天数
  maxRange?: number
}

const defaultOptions: HookOptions = {
  disableFuture: true,
  maxRange: 30
}

export default function useRangeDate(options?: HookOptions) {
  const innerOptions = { ...defaultOptions, ...options }
  if (!innerOptions.default) {
    innerOptions.default = [
      dayjs().subtract(5, 'minute').unix() * 1000,
      dayjs().unix() * 1000
    ]
  }
  const today = dayjs()
  const dates = ref<[DateValue, DateValue]>(innerOptions!.default!)

  const startTime = computed(() => {
    return dayjs(dates.value[0]).unix()
  })

  const endTime = computed(() => {
    return dayjs(dates.value[1]).unix()
  })

  const shortcuts: LabelValue<DateValue[]>[] = [
    {
      label: '最近1分钟',
      value: [today.subtract(1, 'minute').unix() * 1000, today.unix() * 1000]
    },
    {
      label: '最近5分钟',
      value: [today.subtract(6, 'minute').unix() * 1000, today.unix() * 1000]
    },
    {
      label: '最近10分钟',
      value: [today.subtract(10, 'minute').unix() * 1000, today.unix() * 1000]
    }
    // {
    //   label: '最近7天',
    //   value: [today.subtract(7, 'day').unix() * 1000, today.unix() * 1000]
    // }
  ]

  function disabledDate(date: Date) {
    if (options?.disableFuture && dayjs(date).isAfter(dayjs())) {
      return true
    }
    if (dates && dates.value.length) {
      const [start, end] = dates.value
      const tooLate =
        !!start &&
        Math.abs(
          (new Date(date).getTime() - (start as number)) / (86400 * 1000)
        ) > innerOptions.maxRange!
      const tooEarly =
        !!end &&
        Math.abs(
          (new Date(date).getTime() - (end as number)) / (86400 * 1000)
        ) > innerOptions.maxRange!
      return tooEarly || tooLate
    }
    return false
  }

  function handleRangeDateSelect(valString: any, value: any) {
    dates.value = value
  }

  return {
    dates,
    shortcuts,
    startTime,
    endTime,
    disabledDate,
    handleRangeDateSelect
  }
}
